/**
 * Copyright [2010] [Tom Cramer (TomCee)]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 */
package nl.tomcee.dashboard;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
import se.datadosen.component.JLinkLabel;
import se.datadosen.component.JSmartTextArea;
import se.datadosen.jalbum.AlbumBean;
import se.datadosen.jalbum.Config;
import se.datadosen.jalbum.JAlbumContext;
import se.datadosen.util.IO;

/**
 *
 * @author Tom
 * @version 1.6
 * @since 1.6
 * <pre>
 * recompiled because of change in jAlbum core 9.4
 * renamed to Dashboard.jaext to make it self-install
 * </pre>
 * @since 1.5 
 * <pre>
 * added to google code projects
 * </pre>
 * @since 1.4
 * <pre>
 * catched the error when no project jap is selected
 * </pre>
 * @since 1.3
 * <pre>
 * minor bug fix
 * </pre>
 * @since 1.2
 * <pre>
 * changed properties read method so that utf-8 is displayed properly
 * </pre>
 * @since 1.1
 * <pre>
 * added the current project.jap
 * </pre>
 */
public class Dashboard extends javax.swing.JFrame {

    private JTabbedPane tabs;
    private JPanel skinVarsPanel;
    private JPanel userVarsPanel;
    private JPanel enginePanel;
    private AlbumBean engine;
    private Map map;
    private JScrollPane sp;
    private JPanel jaDefaultPanel;
    private JPanel projectJapPanel;
    private JPanel allPropsPanel;
    private File skinDir;
    private File imageDir;
    private File selectedDir;
    private Properties props;
    private File f;
    private JPanel infoPanel;
    private File myAlbumsLocation;
    private JLabel label;
    private String version;
    private JAlbumContext context;

    public Dashboard() {
        version = "1.6";
        initComponents();
    }

    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Dashboard");
        setIconImage(new ImageIcon(getClass().
                getResource("favicon.gif")).getImage());
        setLocationByPlatform(true);
        buildMenu();
        context = JAlbumContext.getInstance();
        context.getFrame().ui2Engine();
        engine = context.getEngine();
        skinDir = context.getSkinDir();
        imageDir = new File(engine.getDirectory());
        myAlbumsLocation = new File(Config.getConfig().getMyAlbumsLocation());
        f = new File("");
        label = new JLabel();
        createBasePanel();
        add(tabs, BorderLayout.CENTER);
        pack();
    }

    private void buildMenu() {
        JMenuBar menubar = new JMenuBar();
        JMenuItem aboutMenuItem = new JMenuItem("About");
        aboutMenuItem.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String aboutText = "<html>Dashboard<br>version: " + version
                        + "<br>author: Tom<br>Click to visit the Dashboard homepage!</html>";
                JLinkLabel aboutLabel = new JLinkLabel("http://tomcee.jalbum.net/Dashboard project/", aboutText);
                JOptionPane.showMessageDialog(rootPane, aboutLabel, "About:",
                        JOptionPane.INFORMATION_MESSAGE, new ImageIcon(getClass().
                        getResource("favicon.gif")));
            }
        });
        menubar.add(aboutMenuItem);
        this.setJMenuBar(menubar);
    }

    private JScrollPane getScrollPane(Map map) {
        JSmartTextArea ta = new JSmartTextArea();
        ta.setOpaque(false);
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        ta.setFont(new java.awt.Font("Tahoma", 0, 11));
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entr = (Map.Entry) iter.next();
            ta.append(entr.getKey() + " = " + entr.getValue() + "\n");
        }
        sp = new JScrollPane(ta);
        sp.setOpaque(false);
        sp.setPreferredSize(new Dimension(400, 300));
        sp.setBorder(BorderFactory.createCompoundBorder());
        ta.setCaretPosition(0);
        return sp;
    }

    private void createInfoPanel() {
        infoPanel = new JPanel();
        infoPanel.setLayout(new MigLayout());
        f = new File(skinDir, "skin.properties");
        props = new Properties();
        try {
            props.load(new FileInputStream(f.getAbsolutePath()));
        } catch (IOException ex) {
            Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
        }
        map = new TreeMap(props);
        getScrollPane(map);
        infoPanel.add(sp);
    }

    private void createEnginePanel() {
        enginePanel = new JPanel();
        enginePanel.setLayout(new MigLayout());
        props = new Properties();
        props.setProperty("account profile name", engine.getAccountProfileName());
        props.setProperty("closeup directory", engine.getCloseupDirectory());
        props.setProperty("cpu cores", String.valueOf(engine.getCpuCores()));
        props.setProperty("directory", engine.getDirectory());
        props.setProperty("interpreted output directory", engine.getInterpretedOutputDirectory().getAbsolutePath());
        props.setProperty("output directory", engine.getOutputDirectory());
        props.setProperty("remote directory", engine.getRemoteDirectory());
        props.setProperty("resource directory", engine.getResourceDirectory());
        props.setProperty("skin", engine.getSkin());
        props.setProperty("style", engine.getStyle());
        map = new TreeMap(props);
        getScrollPane(map);
        enginePanel.add(sp);
    }

    private void createSkinVarsPanel() {
        skinVarsPanel = new JPanel();
        skinVarsPanel.setLayout(new MigLayout());
        map = new TreeMap(engine.getSkinVariables());
        getScrollPane(map);
        skinVarsPanel.add(sp);
    }

    private void createUserVarsPanel() {
        userVarsPanel = new JPanel();
        userVarsPanel.setLayout(new MigLayout());
        map = new TreeMap(engine.getUserVariables());
        getScrollPane(map);
        userVarsPanel.add(sp);
    }

    private void createJaDefaultPanel() {
        jaDefaultPanel = new JPanel();
        jaDefaultPanel.setLayout(new MigLayout());
        f = new File(java.lang.System.getProperty("user.home"), ".jalbum-defaults.jap");
        if (f.exists()) {
            try {
                map = new TreeMap(IO.readPropertyFile(f));
            } catch (IOException ex) {
                Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
            }
            getScrollPane(map);
            jaDefaultPanel.add(sp);
        }
    }

    private void createProjectJapPanel() {
        projectJapPanel = new JPanel();
        projectJapPanel.setLayout(new MigLayout());

        f = new File(context.getFrame().projectChooser.getSelectedFile().getAbsolutePath());
        if (f.exists()) {
            try {
                map = new TreeMap(IO.readPropertyFile(f));
            } catch (IOException ex) {
                Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
            }
            getScrollPane(map);
            projectJapPanel.add(new JLabel("<html><i><b>" + f.getName() + ":</b></i></html>"), "wrap");
            projectJapPanel.add(sp);
        }
    }

    private void createAllPropsPanel() {
        allPropsPanel = new JPanel();
        allPropsPanel.setLayout(new MigLayout());

        JButton openSkinDirButton = new JButton("open skin directory");
        allPropsPanel.add(openSkinDirButton);
        JButton openImageDirButton = new JButton("open image directory");
        allPropsPanel.add(openImageDirButton);
        JButton openMyAlbumsLocationButton = new JButton("open my albums location");
        allPropsPanel.add(openMyAlbumsLocationButton, "wrap");
        openSkinDirButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectedDir = skinDir;
                buttonActionPerformed(evt);
            }
        });
        openImageDirButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectedDir = imageDir;
                buttonActionPerformed(evt);
            }
        });
        openMyAlbumsLocationButton.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectedDir = myAlbumsLocation;
                buttonActionPerformed(evt);
            }
        });
        allPropsPanel.add(label, "wrap");
    }

    private void buttonActionPerformed(java.awt.event.ActionEvent evt) {

        props = new Properties();
        JFileChooser fc = new JFileChooser();
        fc.setCurrentDirectory(selectedDir);
        fc.setAcceptAllFileFilterUsed(false);
        fc.addChoosableFileFilter(new CustomFilter());
        int returnVal = fc.showOpenDialog(rootPane);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            f = fc.getSelectedFile();
            try {
                map = new TreeMap(IO.readPropertyFile(f));
            } catch (IOException ex) {
                Logger.getLogger(Dashboard.class.getName()).log(Level.SEVERE, null, ex);
            }
            allPropsPanel.remove(sp);
            allPropsPanel.remove(label);
            getScrollPane(map);
            label.setText("<html><i><b>" + f.getName() + ":</b></i></html>");
            allPropsPanel.add(label, "wrap");
            allPropsPanel.add(sp, "span");
            allPropsPanel.validate();
        }
    }

    private void createBasePanel() {
        tabs = new JTabbedPane();
        createInfoPanel();
        createEnginePanel();
        createSkinVarsPanel();
        createUserVarsPanel();
        createJaDefaultPanel();
        createProjectJapPanel();
        createAllPropsPanel();

        tabs.addTab("skin vars:", skinVarsPanel);
        tabs.addTab("user vars:", userVarsPanel);
        tabs.add("ja defaults:", jaDefaultPanel);
        tabs.addTab("engine:", enginePanel);
        tabs.add("project jap:", projectJapPanel);
        tabs.add("props/japs:", allPropsPanel);
        tabs.addTab("skin info:", infoPanel);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Dashboard().setVisible(true);
            }
        });
    }
}//end

